package com.yunhaikeji.core.poi;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * html的table转化为Excel
 * @author bean
 *
 */
public class HtmlToExcel {
	
	private static final Logger log = LoggerFactory.getLogger(HtmlToExcel.class);
	
	public static Excel convert(String html, Excel e){
		Document doc = Jsoup.parse(html);
		Boolean hasHeader = false;
		Element header = getHeader(doc, hasHeader);
		int row = 0;
		fillTds(header.getElementsByTag("td"), row++, 0, e);
		Elements trs = getTrs(doc);
		if(!hasHeader){
			trs.remove(0);
		}
		fillTrs(trs, row, e);
		return e;
	}
	
	private static void fillTrs(Elements trs, int row, Excel e){
		if(e.getSheet() == null){
			
			log.error("no sheet");
			
			throw new RuntimeException("请先创建sheet--使用Excel.createSheet方法创建");
		}
		int lastRowSpan = 0;//这边有个bug，需要用栈解决,先这样把
		for(Element tr : trs){
			int col = 0;
			if(lastRowSpan != 0){
				++col;
				--lastRowSpan;
			}
			int l = fillTds(tr.getElementsByTag("td"), row, col, e);
			if(l != 0){
				lastRowSpan = l - 1;
			}
			++row;
		}
	}
	
	private static int fillTds(Elements tds, int row, int col, Excel e){
		if(tds == null){
			return 0;
		}
		if(e.getSheet() == null){
			
			log.error("no sheet");
			
			throw new RuntimeException("请先创建sheet--使用Excel.createSheet方法创建");
		}
		int lastRowSpan = 0;
		for(Element td : tds){
			String colspan = td.attr("colspan");
			String rowspan = td.attr("rowspan");
			String value = td.text();
			//e.setValue(row, col, value, e.getCenterStyle(), 5000, 20);
			e.setValue(row, col, value, e.getCenterStyle(), 20);
			if(!rowspan.equals("")){
				lastRowSpan = Integer.parseInt(rowspan);
				int row2 = row + lastRowSpan - 1;
				e.merge(row, col, row2, col);
			}
			if(!colspan.equals("")){
				int col2 = col + Integer.parseInt(colspan) - 1;
				e.merge(row, col, row, col2);
				col = col2;
			}
			++col;
		}
		return lastRowSpan;
	}
	
	private static Elements getTrs(Document doc){
		return doc.getElementsByTag("tr");
	}
	
	private static Element getHeader(Document doc, Boolean hasHeader){
		Elements es = doc.getElementsByTag("thead");
		if(es == null || es.size() == 0){
			es = getTrs(doc);
			if(es != null && es.size() != 0){
				hasHeader = false;
				return es.first();
			}
			return null;
		}else {
			hasHeader = true;
			return es.first();
		}
	}
}
